import {
  getLoginUserUsingGET,
  uploadFileUsingPOST,
} from '@/services/api/userController';
import {history} from '@@/core/history';
import {UploadOutlined} from '@ant-design/icons';
import {DownloadOutlined} from '@ant-design/icons';
import {
  Button,
  Col,
  Form,
  Input,
  message,
  Radio,
  Row,
  Select,
  Space,
  Spin,
  Upload,
} from 'antd';
import type {FormInstance} from 'antd/es/form';
import React, {useState} from 'react';

const {TextArea} = Input;

const FileHandling: React.FC = () => {
  const [result, setResult] = useState<API.UploadFileResult>();
  const [submitting, setSubmitting] = useState<boolean>(false);
  const formRef = React.useRef<FormInstance>(null);
  const [isHidden, setIsHidden] = useState(true);
  const [downHidden, setDownHidden] = useState(true);

  const handleSelectChange = (value: string) => {
    const shouldHide = value.endsWith('xml') || value.endsWith('json');
    setIsHidden(!shouldHide);
  };

  const onResultChange = () => {
    if (result?.result) {
      formRef.current?.setFieldsValue({result: result.result});
    }
    return result?.result;
  };

  const onContentChange = () => {
    if (result?.resultContent) {
      formRef.current?.setFieldsValue({content: result.resultContent});
    }
    return '';
  };

  const onStatusChange = () => {
    if (result?.valid === null) {
      return '';
    } else if (result?.valid === true) {
      return 'warning';
    } else if (result?.valid === false) {
      return 'error';
    }
  };


  const handleDownloadOriginFile = () => {
    // 根据你的具体逻辑获取原始数据文件的URL
    const originFileUrl = result?.inputPath; // 替换为实际的文件URL

    if (originFileUrl) {
      const urlParts = originFileUrl.split("/");
      const fileName = urlParts[urlParts.length - 1];

      const link = document.createElement("a");
      link.href = originFileUrl;
      link.download = fileName;
      link.style.display = "none";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } else {
      message.error("暂时没有文件可下载");
    }
  };


  const handleDownloadResultFile = () => {
    const resultFileUrl = result?.outputPath;

    if (resultFileUrl) {
      const urlParts = resultFileUrl.split("/");
      const fileName = urlParts[urlParts.length - 1];

      const link = document.createElement("a");
      link.href = resultFileUrl;
      link.download = fileName;
      link.style.display = "none";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } else {
      message.error("暂时没有文件可下载");
    }
  };

  const handleTextAreaChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    formRef.current?.setFieldsValue({content: e.target.value});
  };


  //  文本框默认内容
  const fetchUserInfo = async () => {
    try {
      const res = await getLoginUserUsingGET();
      return res.data;
    } catch (error) {
      history.push('/user/login');
    }
    return undefined;
  };

  const onFinish = async (values: any) => {
    //避免重复提交
    if (submitting) {
      return;
    }
    setSubmitting(true);
    setDownHidden(false);
    const user = await fetchUserInfo();
    const params = {
      ...values,
      id: user?.id,
      content: undefined,
      file: undefined,
    };
    console.log(params);
    try {
      const res = await uploadFileUsingPOST(
        params,
        {},
        values?.file?.file?.originFileObj,
        values?.content,
      );
      if (!res?.data) {
        message.error('请求失败');
      } else if (res.code === 0) {
        message.success('请求成功！');
        setResult(res.data);
      } else {
        message.error('请求失败：' + res.message);
      }
    } catch (e: any) {
      message.error('请求失败：' + e.message);
    }
    setSubmitting(false);
  };

  return (
    <div className="file_handling">
      <Form
        ref={formRef}
        name="file_handling"
        onFinish={onFinish}
        // style={{ maxWidth: 600 }}
        layout="horizontal"
      >
        <Form.Item label="服务类型">
          <span className="ant-form-text">文件服务</span>
        </Form.Item>
        <Row>
          <Col xs={{span: 1, offset: 0}} lg={{span: 6, offset: 0}}>
            <Form.Item name="content">
              <TextArea
                showCount
                // maxLength={9999}
                style={{height: 470, width: 400, marginBottom: 24}}
                allowClear={true}
                wrap="off"
                status={onStatusChange()}
                onChange={handleTextAreaChange}
                placeholder="请输入你要处理的字符串"
                value={onContentChange()}
              />
            </Form.Item>
          </Col>
          <Col xs={{span: 11, offset: 1}} lg={{span: 6, offset: 3}}>
            <Form.Item
              name="doType"
              label="服务选项"
              rules={[{required: true, message: '请选择你要的服务选项！'}]}
              style={{marginTop: '60px'}}
            >
              <Select
                options={[
                  {value: 'json2csv', label: 'json转csv'},
                  {value: 'json2xml', label: 'json转xml'},
                  {value: 'json2yaml', label: 'json转yaml'},
                  {value: 'jsonValid', label: 'json格式验证'},
                  {value: 'jsonFormat', label: 'json格式化'},
                  {value: 'jsonCompress', label: 'json压缩'},
                  {value: 'csv2json', label: 'csv转json'},
                  {value: 'csv2xml', label: 'csv转xml'},
                  {value: 'csv2yaml', label: 'csv转yaml'},
                  {value: 'csvValid', label: 'csv格式验证'},
                  {value: 'csvFormat', label: 'csv格式化'},
                  {value: 'xml2json', label: 'xml转json'},
                  {value: 'xml2csv', label: 'xml转csv'},
                  {value: 'xml2yaml', label: 'xml转yaml'},
                  {value: 'xmlValid', label: 'xml格式验证'},
                  {value: 'xmlFormat', label: 'xml格式化'},
                  {value: 'xmlCompress', label: 'xml压缩'},
                  {value: 'yaml2json', label: 'yaml转json'},
                  {value: 'yaml2csv', label: 'yaml转csv'},
                  {value: 'yaml2xml', label: 'yaml转xml'},
                  {value: 'yamlValid', label: 'yaml格式验证'},
                  {value: 'yamlFormat', label: 'yaml格式化'},
                ]}
                onChange={handleSelectChange}
              />
            </Form.Item>

            <Form.Item name="minify" label="结果是否压缩(JSON、XML)" hidden={isHidden}>
              <Radio.Group defaultValue="false">
                <Radio value="true">是</Radio>
                <Radio value="false">否</Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item name="file" label="原始数据" style={{marginBottom: '20px'}}>
              <Upload
                name="file"
                listType="picture"
                maxCount={1}
                accept={'.csv,.json,.xml,.yaml'}
                // action={'http://centos/upload'}
              >
                <Button icon={<UploadOutlined/>}>上传原始数据</Button>
              </Upload>
            </Form.Item>
            <Form.Item wrapperCol={{span: 12, offset: 6}}>
              <Space>
                <Button type="primary" htmlType="submit" loading={submitting} disabled={submitting}>
                  提交
                </Button>
                <Button htmlType="reset">重置</Button>
              </Space>
            </Form.Item>
            <Form.Item hidden={downHidden} name="originFile" label="原始数据下载" style={{marginTop: '50px'}}>
              <Button icon={<DownloadOutlined/>} onClick={handleDownloadOriginFile}>下载原始数据</Button>
            </Form.Item>
            <Form.Item hidden={downHidden} name="resultFile" label="结果数据下载" style={{marginTop: '16px'}}>
              <Button icon={<DownloadOutlined/>} onClick={handleDownloadResultFile}>下载结果数据</Button>
            </Form.Item>
          </Col>

          <Col xs={{span: 5, offset: 1}} lg={{span: 6, offset: 1}}>
            <Form.Item name="result">
              <TextArea
                showCount
                readOnly
                // maxLength={9999}
                wrap="off"
                style={{height: 470, width: 400, resize: 'none'}}
                placeholder="在这里将最多展示结果的前5k个字节数据，如需查看全部数据请下载结果文件！"
                value={onResultChange()}
              >
                <Spin spinning={submitting}/>
              </TextArea>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </div>
  );
};
export default FileHandling;
